package com.kgc.provider;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.kgc.api.goods.CarApi;

import com.kgc.api.goods.ShoppingCartApi;
import com.kgc.bean.*;
import com.kgc.constant.ActiveMqConstant;
import com.kgc.mapper.OrderMapper;
import com.kgc.util.RedisUtils;
import com.kgc.util.ResultBuildUtil;
import com.kgc.util.ReturnResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import springfox.documentation.annotations.ApiIgnore;


import java.util.*;
import java.util.concurrent.atomic.AtomicReference;

@Service
@Slf4j
public class CarProvider implements CarApi {
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private ShoppingCartApi shoppingCartApi;
    @Autowired
    private CarActiveMqQueueProvider carActiveMqQueueProvider;
    @Autowired
    private OrderMapper orderMapper;


    //1.加入购物车功能
    @Override
    public ReturnResult<Map<String, Object>> addToShoppingCart(GoodsCarinfo goodsCarinfo, User user, String token, String goodsId, Integer businessid) {
        log.info("+++++++++++++++++++++++user:{}", user.toString());
        Map<String, Object> returnData = new HashMap<>();
        //判断redis里面有没有用户的购物车信息， 有 发消息队列， 没有 去数据库取用户购物车信息并将信息存储到redis 再发消息队列
        if (null == redisUtils.get("cart:" + user.getUserId())) {
            if (shoppingCartApi.userIsHaveShoppingCart(user.getUserId())) {
                ShoppingCart shoppingCart = shoppingCartApi.queryUserShoppingCart(user.getUserId(), goodsId);
                redisUtils.set("cart:" + user.getUserId(), JSON.toJSONString(shoppingCart));
            } else {
                shoppingCartApi.assignAShoppingCartToTheUser(user.getUserId(), goodsId, businessid);
                ShoppingCart shoppingCart = shoppingCartApi.queryUserShoppingCart(user.getUserId(), goodsId);
                redisUtils.set("cart:" + user.getUserId(), JSON.toJSONString(shoppingCart));
            }
        }
        //发消息队列 要求修改redis中的购物车信息
        goodsCarinfo.setUserid(user.getUserId());
        carActiveMqQueueProvider.sendMessageToQueue(ActiveMqConstant.QUEUE_NAME_TEST, JSON.toJSONString(goodsCarinfo));
        returnData.put("msg", "加入购物车成功！去查看购物车吧！");
        return ResultBuildUtil.success(returnData);
    }
    //2.查看购物车功能

    public ReturnResult<Map<String, Object>> checkTheShoppingCart(User user, @ApiIgnore String goodsId, Integer businessid) {
        Map<String, Object> returnData = new HashMap<>();
        if (null == redisUtils.get("cart:" + user.getUserId())) {
            if (shoppingCartApi.userIsHaveShoppingCart(user.getUserId())) {
                ShoppingCart shoppingCart = shoppingCartApi.queryUserShoppingCart(user.getUserId(), goodsId);
                redisUtils.set("cart:" + user.getUserId(), JSON.toJSONString(shoppingCart));
            } else {
                shoppingCartApi.assignAShoppingCartToTheUser(user.getUserId(), goodsId, businessid);
                ShoppingCart shoppingCart = shoppingCartApi.queryUserShoppingCart(user.getUserId(), goodsId);
                redisUtils.set("cart:" + user.getUserId(), JSON.toJSONString(shoppingCart));
            }
        }

        Object obj = redisUtils.get("cart:" + user.getUserId());
        ShoppingCart shoppingCart = JSON.parseObject(obj.toString(), ShoppingCart.class);
        List carinfoList = JSON.parseObject(shoppingCart.getCarinfolist(), List.class);
        returnData.put("carinfoList", carinfoList);
        ResultBuildUtil.success(returnData);
        return ResultBuildUtil.success(returnData);
    }

    //3.删除购物车某个商品
    @Override
    public ReturnResult<Map<String, Object>> deleteAnItemInTheShoppingCart(String goodsId, Integer businessid, User user) {
        Map<String, Object> returnData = new HashMap<>();
        if (null == redisUtils.get("cart:" + user.getUserId())) {
            if (shoppingCartApi.userIsHaveShoppingCart(user.getUserId())) {
                ShoppingCart shoppingCart = shoppingCartApi.queryUserShoppingCart(user.getUserId(), goodsId);
                redisUtils.set("cart:" + user.getUserId(), JSON.toJSONString(shoppingCart));
            } else {
                shoppingCartApi.assignAShoppingCartToTheUser(user.getUserId(), goodsId, businessid);
                ShoppingCart shoppingCart = shoppingCartApi.queryUserShoppingCart(user.getUserId(), goodsId);
                redisUtils.set("cart:" + user.getUserId(), JSON.toJSONString(shoppingCart));
            }
        }
        Object obj = redisUtils.get("cart:" + user.getUserId());
        ShoppingCart shoppingCart = JSON.parseObject(obj.toString(), ShoppingCart.class);
        List carinfoList = JSON.parseObject(shoppingCart.getCarinfolist(), List.class);
        AtomicReference<Boolean> flag = new AtomicReference<>(true);
        List<GoodsCarinfo> list = new ArrayList<>();
        if (carinfoList != null) {
            carinfoList.forEach(object -> {

                GoodsCarinfo gcinfo = JSON.parseObject(object.toString(), GoodsCarinfo.class);
                log.info(gcinfo.toString());
                log.info("{}：{}", goodsId, businessid);
                log.info(String.valueOf(gcinfo.getGoodsid().equals(goodsId) && gcinfo.getBusinessid().equals(businessid)));
                if (gcinfo.getGoodsid().equals(goodsId) && gcinfo.getBusinessid().equals(businessid)) {
                    flag.set(false);
                    returnData.put("msg", "找到并删除，");
                    log.info("++++++++++++找到并删除++++++++++");

                } else {
                    GoodsCarinfo carinfo = JSON.parseObject(object.toString(), GoodsCarinfo.class);
                    list.add(carinfo);
                }
            });
            carinfoList = list;
            log.info("++++++++++++删除{}后carinfoList:{}++++++++++", goodsId, carinfoList.toString());
        } else {
            carinfoList = new ArrayList<>();
        }
        if (flag.get()) {
            log.info("++++++++++++购物车中未找到该商品，删除失败++++++++++");
            return ResultBuildUtil.fail("3004", "购物车中无该商品，删除失败");

        }
        shoppingCart.setCarinfolist(JSON.toJSONString(carinfoList));
        redisUtils.set("cart:" + user.getUserId(), shoppingCart);
        returnData.put("carinfoList", carinfoList);
        return ResultBuildUtil.success(returnData);
    }

    //4.清空购物车
    @Override
    public ReturnResult<Map<String, Object>> emptyShoppingCart(User user, String goodsId, Integer businessid) {
        Map<String, Object> returnData = new HashMap<>();
        if (null == redisUtils.get("cart:" + user.getUserId())) {
            if (shoppingCartApi.userIsHaveShoppingCart(user.getUserId())) {
                ShoppingCart shoppingCart = shoppingCartApi.queryUserShoppingCart(user.getUserId(), goodsId);
                redisUtils.set("cart:" + user.getUserId(), JSON.toJSONString(shoppingCart));
            } else {
                shoppingCartApi.assignAShoppingCartToTheUser(user.getUserId(), goodsId, businessid);
                ShoppingCart shoppingCart = shoppingCartApi.queryUserShoppingCart(user.getUserId(), goodsId);
                redisUtils.set("cart:" + user.getUserId(), JSON.toJSONString(shoppingCart));
            }
        }
        Object obj = redisUtils.get("cart:" + user.getUserId());
        ShoppingCart shoppingCart = JSON.parseObject(obj.toString(), ShoppingCart.class);
        shoppingCart.setCarinfolist("");
        redisUtils.set("cart:" + user.getUserId(), JSON.toJSONString(shoppingCart));

        obj = redisUtils.get("cart:" + user.getUserId());
        shoppingCart = JSON.parseObject(obj.toString(), ShoppingCart.class);
        List carinfoList = JSON.parseObject(shoppingCart.getCarinfolist(), List.class);
        if (carinfoList != null && carinfoList.size() > 0) {
            return ResultBuildUtil.fail("3001", "购物车清除失败");
        } else {
            returnData.put("msg", "购物车已经清空，前往购物车查看吧。");
        }
        return ResultBuildUtil.success(returnData);
    }

    //    插入carinfolist操作
    public List<GoodsItem> selectcarinfolist(String goodsId) {
        return orderMapper.queryorderitem(goodsId);
    }

}

